# coding=utf8
import requests
import itchat
import urllib3.contrib.pyopenssl

KEY = '8edce3ce905a4c1dbb965e6b35c3834d'



# 请求获取人工智能回复
def get_response(msg):
    apiUrl = 'http://www.tuling123.com/openapi/api'
    data = {
        'key': KEY,
        'info': msg,
        'userid': 'wechat-robot',
    }
    try:
        r = requests.post(apiUrl, data=data).json()
        return r.get('text')
    except:
        return


# 单聊
@itchat.msg_register(itchat.content.TEXT)
def tuling_reply(msg):
    defaultReply = 'I received: ' + msg['Text']
    reply = get_response(msg['Text'])
    return reply or defaultReply



# 群聊
@itchat.msg_register([itchat.content.TEXT], isGroupChat=True)
def group_reply_text(msg):
    # 消息来自于哪个群聊
    chatroom_id = msg['FromUserName']
    # 发送者的昵称
    username = msg['ActualNickName']
    # 指定房间名
    if chatroom_id == '一群沙雕':
        reply = get_response(msg['Text'])
        # 拿不到人工智能就回发
        defaultReply = msg['Text']
        itchat.send(reply or defaultReply)


urllib3.contrib.pyopenssl.inject_into_urllib3()
itchat.auto_login(hotReload=True)
itchat.run()
